// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import router from './router/Index'
import store from './store/index'
import App from './App'
import IVIEW from 'iview';
Vue.use(IVIEW)
import 'iview/dist/styles/iview.css';
import { AjaxPlugin} from 'vux'
Vue.use(AjaxPlugin)
require('es6-promise').polyfill()


import 'quill/dist/quill.core.css'
import '../static/css/quilleditor.css'
import QuillEditor from 'vue-quill-editor';
import ImageResize from 'quill-image-resize-module';
Quill.register('modules/imageResize', ImageResize);
Vue.use(QuillEditor);


import { Message, Notice} from 'iview'
Message.config({
    duration: 3,
});
Notice.config({
    duration: 3,
});
Vue.prototype.$Message = Message
Vue.prototype.$Notice = Notice

import qs from 'qs'
import axios from 'axios'
Vue.prototype.$http = axios
Vue.http.defaults.baseURL = process.env.API_PATH;
Vue.http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Vue.http.interceptors.request.use(function (config) {
    if(config.method === 'options' || (config.method === 'post' && config.headers.post['Content-Type']=='application/x-www-form-urlencoded')) {
        config.data = qs.stringify( {
            ...config.data
        })
    }      
    return config;
  }, function (error) {
    loadinginstace.close()
    return Promise.reject(error);
})


Vue.http.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    // 返回 401 清除token信息并跳转到登录页面
                    // store.commit(types.LOGOUT);
                    if('Login' !=router.currentRoute.name){
                        router.replace({
                            path: 'login',
                            query: {redirect: router.currentRoute.fullPath}
                        })
                    }
            }
        }
        return Promise.reject(error.response.data)   // 返回接口返回的错误信息
});


router.beforeEach( (to, from, next) =>{
    if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
        if (store.state.loginStatus) {  // 通过vuex state获取当前的token是否存在
            next();
        }
        else {
            if(window.localStorage.getItem("token")!=undefined){
                let expires = window.localStorage.getItem('expires')
                let current = (new Date()).getTime()

                if(current<expires){

                    let token = window.localStorage.getItem('token')
                    let refreshToken = window.localStorage.getItem('refreshToken')
                    store.dispatch('setToken',token)
                    store.dispatch('setRefreshToken',refreshToken)
                    store.dispatch('setExpires',expires)
                    next();
                }else{
                    window.localStorage.setItem('token','')
                    next({
                        path: '/login',
                        query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
                    })
                }
            }
            else{
                next({
                    path: '/login',
                    query: {redirect: to.fullPath}  // 将跳转的路由path作为参数，登录成功后跳转到该路由
                })
            }
        }
    }
    else {
        next();
    }
})


router.afterEach( (to) =>{;
    // Vue.$vux.bus && Vue.$vux.bus.$emit('vux:after-view-enter')
})


Vue.config.productionTip = false


import '../static/css/main.css'
Vue.prototype.goback = function (){router.go(-1)}
Vue.prototype.checkPasswordRule=function(value){
    // let b = /^(?=.*[0-9].*)(?=.*[A-Za-z].*).{8,16}$/.test(value)
    let _len = value.length
    let b = _len>=8 && _len<=16
    return {
        valid: b,
        // msg: b?'':'密码必须包含字母和数字，且最少8位最长16位'
        msg: b?'':'密码长度最少8位最长16位'
    }
}
Vue.prototype.setTitle = function (title){
    window.document.title=undefined==title?'管理系统平台':title+' - 管理系统平台'
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).dateFormat("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).dateFormat("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Vue.prototype.dateFormat = function (vDate,fmt) { //author: meizz 
    var o = {
        "M+": vDate.getMonth() + 1, //月份 
        "d+": vDate.getDate(), //日 
        "h+": vDate.getHours(), //小时 
        "m+": vDate.getMinutes(), //分 
        "s+": vDate.getSeconds(), //秒 
        "q+": Math.floor((vDate.getMonth() + 3) / 3), //季度 
        "S": vDate.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (vDate.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

import FastClick from 'fastclick'
FastClick.attach(document.body)
/* eslint-disable no-new */
new Vue({
  router,store,
  render: h => h(App)
}).$mount('#app-box')
